package com.zhenbao.system.controller;


import com.zhenbao.common.pojo.Result;
import com.zhenbao.common.pojo.StatusCode;
import com.zhenbao.system.pojo.Admin;
import com.zhenbao.system.service.AdminService;
import com.zhenbao.system.util.JwtUtil;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {


    @Autowired
    private AdminService adminService;
    /***
     * 新增数据
     * @param admin
     * @return
     */
    @PostMapping
    public Result add(@RequestBody Admin admin){
        adminService.add(admin);
        return new Result(true,StatusCode.OK,"添加成功");
    }

    @PostMapping("/login")
    public Result login(@RequestBody Admin admin){
        boolean login = adminService.login(admin);
        if (login){
            //密码正确
            //获得用户名放入集合
            Map<String,String> map = new HashMap();
            map.put("username",admin.getLoginName());
            //生成一个jwt令牌，返回到客户端
            String jwt = JwtUtil.createJWT(UUID.randomUUID().toString(), admin.getLoginName(), null);
            map.put("token",jwt);
            return new Result(true,StatusCode.OK,"登陆成功",map);
        }else {
            return new Result(false,StatusCode.ERROR,"登陆失败");
        }
    }
}
